//
//  CJSplashGMAdapter.m
//  CJModileGMAdapter
//
//  Created by shanghailingye on 2024/4/24.
//

#import "CJSplashToBidAdapter.h"

@interface CJSplashToBidAdapter()<CJSplashAdDelegate>
/// 广告实例
@property (nonatomic, strong) CJSplashAd *splashAd;
@property (nonatomic, weak) id<AWMCustomSplashAdapterBridge> bridge;
// 是否是bidding
@property (nonatomic, assign) BOOL isBidding;
@property (nonatomic, assign) BOOL isReady;

@end

@implementation CJSplashToBidAdapter


- (instancetype)initWithBridge:(id<AWMCustomSplashAdapterBridge>)bridge {
    self = [super init];
    if (self) {
        _bridge = bridge;
    }
    return self;
}

- (BOOL)mediatedAdStatus {
    return self.isReady;
}

- (void)loadAdWithPlacementId:(NSString *)placementId parameter:(AWMParameter *)parameter {
    _isBidding = parameter.isHeaderBidding;
    _isReady = false;
    UIViewController *viewController = [self.bridge viewControllerForPresentingModalView];
    UIView *bottomView = [parameter.extra objectForKey:AWMAdLoadingParamSPCustomBottomView];
    self.splashAd = [[CJSplashAd alloc] initWithResourceId:placementId rootViewController:viewController customLogoView:bottomView];
    self.splashAd.delegate = self;
    [self.splashAd loadAdData];
}

- (void)showSplashAdInWindow:(UIWindow *)window parameter:(AWMParameter *)parameter {
    [self.splashAd showSplashAdToWindow:window];
}

- (void)didReceiveBidResult:(AWMMediaBidResult *)result {
    NSLog(@"%@", result.win ? @"胜出" : @"竞胜失败");
}

- (void)destory {
    self.splashAd = nil;
}

#pragma mark CJSplashAdDelegate
- (void)splashAdDidLoad:(nonnull CJSplashAd *)splashAd resourceId:(nonnull NSString *)resourceId {
    NSInteger cpm = [self.splashAd getECpm];
    NSDictionary *ext = @{
        AWMMediaAdLoadingExtECPM : cpm ? [NSString stringWithFormat:@"%ld", cpm] : @"0",
    };
    if (_isBidding) { [self.bridge splashAd:self didAdServerResponseWithExt:ext]; }
    self.isReady = true;
    [self.bridge splashAdDidLoad:self];
}

- (void)splashAdLoadFailed:(nonnull CJSplashAd *)splashAd error:(nonnull NSError *)error {
    [self.bridge splashAd:self didLoadFailWithError:error ext:@{}];
}

- (void)splashAdOnClicked:(nonnull CJSplashAd *)splashAd {
    [self.bridge splashAdDidClick:self];
}

- (void)splashAdOnClosed:(nonnull CJSplashAd *)splashAd {
    [self.bridge splashAdDidClose:self];
}

- (void)splashAdOnShow:(nonnull CJSplashAd *)splashAd {
    [self.bridge splashAdWillVisible:self];
}




@end
